<?php
class Person extends MY_SecuredController {

	public function __construct() {
		parent::MY_SecuredController();

		$this->requireRole('User');
		
		$this->load->helper(array('form','url'));
		$this->load->library('form_validation');
		
		$this->lang->load('home');
		$this->lang->load('profile');
	}

	public function edit($civlid) {
		$this->_preRender($civlid);
        $person = PersonModel::getPerson($civlid);
		
		// check permissions: owners can edit everything, admins only if the person belongs to their club
		if (!$this->_checkAdminClub($person)) {
			return false;
		}
        
		if (!$this->input->post('action')) {
			$data['person'] = $person;
			$data['pilot'] = $person->Pilot;

			$this->render('profile/person', $data);
		}
		else {
			if ($this->_submit_validate() === FALSE) {
				//$person = PersonModel::getPerson($civlid);
				$data['person'] = $person;
				$data['pilot'] = $person->Pilot;
				$this->render('profile/person', $data, $this->error(validation_errors('<li>','<li>')));
			}
			else {
				$p = PersonModel::getPerson($civlid);
				$p->merge($_POST);

				try {
					$p->replace();
					$this->redirect('profile/person/edit/'.$civlid,'Person profile updated successfully!');
				}
				catch (Exception $e) {
					$this->render('profile/person', null, $this->error(array(
						'message' => 'Ooops, the profile could not be updated - please try again later.',
						'exception' => $e
					)));
				}
			}
		}
	}
	
	private function _submit_validate() {
		$this->form_validation->set_rules('email_primary', 'E-mail',
			'required|valid_email');

		$this->form_validation->set_rules('name', 'Name',
			'trim|required|xss_clean');

		return $this->form_validation->run();

	}

    private function _getRedirUrl($extras) {
        $baseUrl = 'home';
        $haystack = $extras;
        $needle = 'o:';
        
        if (strpos($haystack, $needle) === FALSE)
            return $baseUrl;
        
        $result = str_replace('-', '/', substr($haystack, strlen($needle)));
        
        return $result;
    }
}
?>
